<template>
  <div class="common-layout">
    <el-container>
      <el-aside width="200px" style="min-height: 100vh; background-color: rgb(22,46,86)">
        <div class="aside-head-info"
             style="width: 200px; height: 80px; align-items: center; justify-items: center; display: flex">
          <span
              style="color: #f9f9f9; display: flex; align-items: center; justify-content: center; width: 200px">欢迎您，食堂管理员</span>
        </div>
        <el-menu style="border: none" :default-active="currentUrl" router background-color="#162E56"
                 text-color="#f9f9f9">
          <el-menu-item index="/restaurant-manager/index">
            <template #title>
              <el-icon>
                <User/>
              </el-icon>
              用户首页
            </template>
          </el-menu-item>
          <el-menu-item index="/restaurant-manager/restaurant-info-maintain">
            <template #title>
              <el-icon>
                <DishDot/>
              </el-icon>
              餐厅信息
            </template>
          </el-menu-item>
          <el-menu-item index="/restaurant-manager/dishes-maintain">
            <template #title>
              <el-icon>
                <Edit/>
              </el-icon>
              菜品维护
            </template>
          </el-menu-item>
          <el-menu-item index="/restaurant-manager/report-reply">
            <template #title>
              <el-icon>
                <Warning/>
              </el-icon>
              投诉回复
            </template>
          </el-menu-item>
          <el-menu-item index="/restaurant-manager/remark-reply">
            <template #title>
              <el-icon>
                <Message/>
              </el-icon>
              评论回复
            </template>
          </el-menu-item>
          <el-menu-item index="/restaurant-manager/recommend-dish-publish">
            <template #title>
              <el-icon>
                <More/>
              </el-icon>
              新品发布
            </template>
          </el-menu-item>
          <el-menu-item index="/restaurant-manager/vote">
            <template #title>
              <el-icon>
                <Collection/>
              </el-icon>
              调查发布
            </template>
          </el-menu-item>
        </el-menu>
      </el-aside>
      <el-container>
        <el-header
            style="box-shadow: 2px 0 6px rgba(0, 21, 41, .36); display: flex; align-items: center; justify-content: space-between">
          <el-breadcrumb :separator-icon="ArrowRight">
            <el-breadcrumb-item v-for="item in route.matched" :to="{path: item.path}">{{ item.meta.title }}
            </el-breadcrumb-item>

          </el-breadcrumb>
          <div class="avatar-container" style="align-items: center; display: flex; justify-content: flex-end">
            <el-dropdown style="display: flex; align-items: center; justify-content: flex-end" placement="bottom">
        <span class="el-dropdown-link"
              style="display: flex; align-items: center;">
          <el-avatar :size="24" :src="avatarSrc" style="margin: 0 5px"/>
          {{ '欢迎您，' + nickname }}
        </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item>个人中心</el-dropdown-item>
                  <el-dropdown-item>退出登录</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </el-header>
        <el-main>
          <div class="app-container">
            <el-form :model="form" ref="formRef" :inline="false" label-width="100px" size="large"
                     style="margin: 20px 0 0 0" :rules="fromRules">
              <el-form-item label="食堂图片">
                <el-upload
                    v-model:file-list="fileList"
                    ref="upload"
                    list-type="picture-card"
                    :on-preview="handlePictureCardPreview"
                    :on-remove="handleRemove"
                    :auto-upload="false"
                    :limit="1"
                    :on-exceed="handleExceed"
                    :on-change="handleSelectedImgChange">
                  <el-icon>
                    <Plus/>
                  </el-icon>
                </el-upload>
              </el-form-item>
              <el-form-item label="食堂名称" prop="restaurantName">
                <el-input v-model="form.restaurantName" placeholder="请输入食堂名称" clearable></el-input>
              </el-form-item>
              <el-form-item label="食堂位置" prop="restaurantLocation">
                <el-input v-model="form.restaurantLocation" placeholder="请输入食堂位置" clearable/>
              </el-form-item>
              <el-form-item label="电子邮箱" prop="email">
                <el-input v-model="form.email" placeholder="请输入电子邮箱" clearable/>
              </el-form-item>
              <el-form-item label="联系电话" prop="phone">
                <el-input v-model="form.phone" placeholder="请输入联系电话" clearable/>
              </el-form-item>
              <el-form-item label="开始营业时间" prop="openingTime">
                <el-time-select
                    v-model="form.openingTime"
                    :max-time="form.closingTime"
                    class="mr-4"
                    placeholder="请输入开始营业时间"
                    start="05:30"
                    step="00:15"
                    end="23:30"/>
              </el-form-item>
              <el-form-item label="结束营业时间" prop="closingTime">
                <el-time-select
                    v-model="form.closingTime"
                    :min-time="form.openingTime"
                    placeholder="请输入结束营业时间"
                    start="05:30"
                    step="00:15"
                    end="23:30"/>
              </el-form-item>
              <el-form-item label="是否停业" prop="status">
                <el-select v-model="form.status" placeholder="请选择是否停业" clearable>
                  <el-option v-for="item in dict_yes_no" :key="item.value" :label="item.label"
                             :value="item.value"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" size="large" @click="submitForm(formRef)">确定</el-button>
                <el-button type="danger" size="large" @click="cancel">取消</el-button>
              </el-form-item>
            </el-form>
            <!--            图片预览对话框-->
            <el-dialog v-model="dialogVisible" :width="dialogWidth">
              <template #header>
                <span>图片预览</span>
              </template>
              <img :src="dialogImageUrl" alt="Preview Image" :width="dialogImageWidth" :height="dialogImageHeight"/>
            </el-dialog>

          </div>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<script setup>
import {useRoute} from "vue-router";
import {ArrowRight} from "@element-plus/icons-vue";
import {dict_yes_no, generalValidatorJudgeIfEmpty} from "../../utils/common.js";
import {ElMessage, genFileId} from "element-plus";
import {queryDetailRestaurantInfo, updateRestaurantInfo} from "../../web-api/resaurant-manager/restaurantMaintain.js";
import {parseTime} from "../../utils/ruoyi.js";
import {baseStaticRecourseAPI, NOW_ENVIRONMENT} from "../../baseAPIConfig.js";
import {handleDataSubmitWithBlob} from "@/utils/dongyan.js";
import {getLocalStorage, KEY_AVATAR, KEY_NICKNAME, KEY_RESTAURANT_ID} from "../../utils/localStorge.js";

let route = useRoute();

// 记录当前路由
let currentUrl = ref()

// 记录当前登录用户昵称
let nickname = ref(getLocalStorage(KEY_NICKNAME))

// 记录当前用户登陆的食堂id
let restaurantId = getLocalStorage(KEY_RESTAURANT_ID);

// 记录当前登录用户头像，后期应该要大改
let avatarSrc = baseStaticRecourseAPI[NOW_ENVIRONMENT] + getLocalStorage(KEY_AVATAR)

// 食堂信息表单
let form = reactive({
  restaurantId: null,
  restaurantName: null,
  restaurantLocation: null,
  email: null,
  phone: null,
  openingTime: null,
  closingTime: null,
  // avatar
  // 营业状态，0表示停业，1表示正常营业
  status: null
})

// 文件传输列表，使用时先从后端初始化一张食堂的图片，这里先写死了
let fileList = ref([{
  name: 'test.png',
  url: 'https://i.b2b168.com/wrzimg.jpg'
}])

// 表单验证规则
let fromRules = reactive({
  restaurantName: [{validator: generalValidatorJudgeIfEmpty("食堂名称不能为空！"), trigger: 'blur'}],
  restaurantLocation: [{validator: generalValidatorJudgeIfEmpty('食堂地点不能为空！'), trigger: 'blur'}],
  email: [{
    validator: (rule, value, callback) => {
      callback()
    }, trigger: 'blur'
  }],
  phone: [{validator: generalValidatorJudgeIfEmpty('食堂联系方式不能为空！'), trigger: 'blur'}],
  openingTime: [{validator: generalValidatorJudgeIfEmpty('食堂开始营业时间不能为空！'), trigger: 'blur'}],
  closingTime: [{validator: generalValidatorJudgeIfEmpty('食堂结束营业时间不能为空！'), trigger: 'blur'}],
  status: [{validator: generalValidatorJudgeIfEmpty('食堂营业状态不能为空！'), trigger: 'blur'}]
})

// 指定对话框的图片src
const dialogImageUrl = ref('')
// 对话框是否可见
const dialogVisible = ref(false)
// 点击删除图片时触发
const handleRemove = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles)
}
// 图片预览
const handlePictureCardPreview = (uploadFile) => {
  // 固定对话框高度为300，宽度成比例
  modifyDialogImageWidthAndHeight();
  // console.log(fileList.value)
  dialogImageUrl.value = uploadFile.url
  dialogVisible.value = true
}

// 上传引用
let upload = ref()

let dialogImageWidth = ref('500px')
let dialogImageHeight = ref('300px')
let dialogWidth = ref('600px')

// 对话框打开之前先把对话框宽度改改
function modifyDialogImageWidthAndHeight() {
  // console.log(fileList.value[0])
  let imageUrl = fileList.value[0].url;
  let image = new Image();
  image.src = imageUrl;
  dialogImageWidth = `${300 * image.width / image.height}px`;
  dialogWidth = `${300 * image.width / image.height + 100}px`
}

// 选取图片超出限制时触发，自动去掉最前一个上传的图片，保留最新上传的图
const handleExceed = (files) => {
  upload.value.clearFiles()
  const file = files[0]
  file.uid = genFileId()
  upload.value.handleStart(file)
}

// 上传文件内容
let restaurantPic = reactive({
  fileContent: ''
})

// 上传图片触发
const handleSelectedImgChange = (ev) => {
  // console.log(ev.raw);
  restaurantPic.fileContent = ev.raw;
}

const requestBasicInfo = () => {
  queryDetailRestaurantInfo(restaurantId).then(res => {
    fileList = ref([{
      name: 'test.png',
      url: 'https://i.b2b168.com/wrzimg.jpg'
    }])
    if (res.data.avatar === null || res.data.avatar === '') {
      fileList.value[0].name = 'fail';
      fileList.value[0].url = '#'
    } else {
      // fileList.value[0].name = res.data.avatar.split("/").slice(-1)[0];
      // fileList.value[0].url = res.data.avatar;
      fileList.value = ref([{
        url: baseStaticRecourseAPI[NOW_ENVIRONMENT] + res.data.avatar,
        name: res.data.avatar.split("/").slice(-1)[0]
      }])
      form.restaurantId = res.data.restaurantId;
      form.restaurantLocation = res.data.restaurantLocation;
      form.restaurantName = res.data.restaurantName;
      form.email = res.data.email;
      form.phone = res.data.phone;
      form.openingTime = res.data.openingTime;
      form.closingTime = res.data.closingTime;
      form.status = res.data.status;
    }
  })
}

// 表单引用
let formRef = ref();

const submitForm = (formEl) => {
  formEl.validate(valid => {
    if (valid) {
      let formData = new FormData()
      formData.append("restaurant", handleDataSubmitWithBlob(form));
      formData.append('restaurantPic', restaurantPic.fileContent);
      updateRestaurantInfo(formData).then(res => {
        ElMessage.success("修改成功！")
        requestBasicInfo();
      }).catch(err => console.log(err))
    }
  })
}

const cancel = () => {
  requestBasicInfo();
}

onBeforeMount(() => {
  // TODO 后端接口写好了再解开
  requestBasicInfo();
})

// TODO 统一调试了再打开
// let restaurantId = getLocalStorage(KEY_RESTAURANT_ID)
// let restaurantId = ref("1738138900769878018")

onMounted(() => {
  currentUrl.value = route.path;
  // console.log(currentUrl);
  // console.log(route)
})
</script>

<style scoped>
.is-active {
  color: #f9f9f9 !important;
  background-color: #47739a;
  border-radius: 20px;
  margin: 0 10px;
}

.el-menu-item {
  margin: 5px 10px !important;
}

.el-menu-item:hover {
  border-radius: 20px;
}

::v-deep .el-dialog__body {
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>